package cn.com.generaldata.os.service.common;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import cn.com.generaldata.os.constant.BillboardConstant;
import cn.com.generaldata.os.constant.FilterConstant;
import cn.com.generaldata.os.dao.intf.BaseDAOInterface;
import cn.com.generaldata.os.paging.Event;
import cn.com.generaldata.os.paging.Filter;
import cn.com.generaldata.os.paging.FilterRule;
import cn.com.generaldata.os.paging.Page;
import cn.com.generaldata.os.paging.Result;
import cn.com.generaldata.os.pojo.Billboard;
import cn.com.generaldata.os.pojo.BillboardUser;
import cn.com.generaldata.os.pojo.Unit;

@Component
public class BillboardService {

	private static Logger log = LoggerFactory.getLogger(BillboardService.class);

	@Autowired
	@Qualifier("baseDAO")
	private BaseDAOInterface<Billboard> billboardDAO;

	@Autowired
	@Qualifier("baseDAO")
	private BaseDAOInterface<BillboardUser> billboardUserDAO;

	public String createBillboard(Billboard billboard, List<Unit> users) {
		if (billboard == null || StringUtils.isBlank(billboard.getBillboardTitle())
				|| StringUtils.isBlank(billboard.getBillboardContent())) {
			// throw new CommonException(ExceptionConstant.MSG_ILLEGAL_PARAMETER);
			log.error("Billboard为空");
			return null;
		}

		// 判断专业名称是否重复
		billboard.setBillboardDate(new Date());
		if (billboard.getId() == null || "".equals(billboard.getId()))
			billboard.setId(UUID.randomUUID().toString().replaceAll("-", ""));
		billboardDAO.saveOrUpdate(billboard);

		// 保存专业与报表类型的关系
		Set<BillboardUser> billboardUsers = new HashSet<BillboardUser>();
		for (Unit user : users) {
			// 默认设置状态为未读，以后有需要判断状态时再进行修改
			BillboardUser billboardUser = new BillboardUser(UUID.randomUUID().toString().replaceAll("-", ""), user,
					billboard, BillboardConstant.STATUS_UNREAD, null);
			billboardUserDAO.saveOrUpdate(billboardUser);
			billboardUsers.add(billboardUser);
		}
		billboard.setBillboardUsers(billboardUsers);
		return billboard.getId();
	}

	public Billboard modifyBillboard(Billboard billboard, List<Unit> users) {
		// 暂无修改Billboard的需求，留待必要时进行实现
		return null;
	}

	public void modifyBillboardUser(BillboardUser billboardUser) {

		Date date = new Date();
		billboardUser.setStatus(BillboardConstant.STATUS_READED);
		billboardUser.setLastReadTime(date);
		billboardUserDAO.save(billboardUser);

	}

	public Billboard queryBillboardById(String id) {
		if (id != null) {
			return billboardDAO.get(Billboard.class, id);
		}
		return null;
	}

	public Result queryBillboards(Filter filter, Page page) {
		List<Billboard> billboards = billboardDAO.find(Billboard.class, filter, page);
		int count = billboardDAO.count(Billboard.class, filter);

		if (page == null) {
			return new Result(1, 1, count, billboards, new ArrayList<Event>());
		}
		return new Result(page.getPageNumber(), page.getPageSize(), count, billboards, new ArrayList<Event>());
	}

	public Result queryBillboardsByUserId(String userId, Page page) {
		if (StringUtils.isBlank(userId)) {
			return null;
		}
		HashMap param = new HashMap();
		String hql = "from Billboard b where exists (select bu.id from BillboardUser as bu where bu.billboard.id=b.id and bu.user.id=:userId) order by billboardDate desc";
		param.put("userId", userId);
		Result hqlParam = billboardDAO.hqlParam(hql, param, page);
		// Filter filter = new Filter();
		// filter.addRule(new FilterRule(FilterConstant.EQUAL, "user.id", userId));
		//
		// List<BillboardUser> billboardUsers = billboardUserDAO.find(BillboardUser.class, filter, null);
		//
		// String[] billboardIds = new String[billboardUsers.size()];
		// for (int i = 0; i < billboardUsers.size(); i++) {
		// billboardIds[i] = billboardUsers.get(i).getBillboard().getId();
		// }
		//
		// filter.getRules().clear();
		// if (billboardIds.length > 0) {
		// filter.addRule(new FilterRule(FilterConstant.COLLECTION, "id", billboardIds));
		// } else {
		// return null;
		// }
		// filter.setOrder(FilterConstant.DESC);
		// filter.setSortBy("billboardDate");
		// queryBillboards(filter, page)
		return hqlParam;
	}

	public Result queryBillboardsAndChangStatus(String userId, Page page) {
		List<BillboardUser> billboardUsers = queryUnReadStatus(userId, page);
		for (int i = 0; i < billboardUsers.size(); i++) {
			modifyBillboardUser(billboardUsers.get(i));
		}

		return queryBillboardsByUserId(userId, page);

	}

	public boolean existUnReadStatus(String userId, Page page) {
		if (StringUtils.isBlank(userId)) {
			// throw new CommonException(ExceptionConstant.MSG_ILLEGAL_PARAMETER);
			log.error("userId为空");
			return false;
		}

		List<BillboardUser> billboardUsers = queryUnReadStatus(userId, page);

		if (billboardUsers.size() > 0) {
			// System.out.println(billboardUsers.size());
			return true;
		} else {
			return false;
		}
	}

	public void removeBillboards(String[] ids) {
		// 暂无删除Billboard的需求，留待必要时实现
	}

	public List<BillboardUser> queryUnReadStatus(String userId, Page page) {
		if (StringUtils.isBlank(userId)) {
			// throw new CommonException(ExceptionConstant.MSG_ILLEGAL_PARAMETER);
			log.error("userId为空");
			return null;
		}

		Filter filter = new Filter();
		filter.addRule(new FilterRule(FilterConstant.EQUAL, "user.id", userId));	
			filter.addRule(new FilterRule(FilterConstant.EQUAL, "status", BillboardConstant.STATUS_UNREAD));

		List<BillboardUser> billboardUsers = billboardUserDAO.find(BillboardUser.class, filter, null);

		return billboardUsers;
	}
}
